import React, {Component} from 'react';
import {
  StyleSheet,
  View,
  Image,
  TouchableOpacity,
  FlatList,
} from 'react-native';
import { connect } from "react-redux";
import { CachedImage } from "react-native-img-cache";
import moment from 'moment';
import _ from 'lodash';
import {
  ActivityIndicator,
  Modal,
  Toast
} from 'antd-mobile-rn';

import { i18n } from '../../../i18n/index';
import { scaleSize } from '../../../utils/screen';
import FontText from '../../components/FontText';
import * as rewardActions from '../actions/rewardActions';
import RewardTips from '../../components/office/RewardTips';
import RewardEditForm from '../../components/office/RewardEditForm';
import RewardAddItem from '../../components/office/RewardAddItem';
import RewardItem from '../../components/office/RewardItem';

class OfficeRewards extends Component {
  componentDidMount() {
    this.props.getRewardList();

    // prefetch products for reward
    this.props.getRewardProducts();
  }

  renderNavigationBar() {
    const _styles = navigationBarStyles;

    return (
      <View style={_styles.navigationBar}>
        <TouchableOpacity
          activeOpacity={0.8}
          onPress={() => this.back()}
          style={_styles.navigationBackButton}
        >
          <Image
            style={_styles.leftArrowImage}
            source={require("../../../access/imgs/back_icon.png")}
          />
          <FontText
            style={_styles.backButtonText}
            font={'book'}
          >
            {i18n.t("btns.back")}
          </FontText>
        </TouchableOpacity>
        <View style={_styles.navigationTitle}>
          <FontText font={'book'} style={_styles.navigationTitleText}>Reward</FontText>
        </View>
        <View style={_styles.navigationRightButtonGroup}>
          <TouchableOpacity
            style={_styles.addButton}
            activeOpacity={0.8}
            onPress={() => this.addReward()}
          >
            <Image style={_styles.addButtonIcon} source={require("../../../access/imgs/add_icon_white.png")} />
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  renderMainView() {
    const _styles = mainViewStyles;
    const { reward } = this.props;
    const showEditForm = !_.isEmpty(reward.editingReward);
    const { products = [] } = reward;

    return (
      <View style={_styles.mainViewContainer}>
        <View style={_styles.mainViewMainPanel}>
          <FlatList
            data = {[...reward.rewards, {}]}
            numColumns={4}
            style={_styles.rewardList}
            keyExtractor={(item, index) => `eval_${index}`}
            columnWrapperStyle={_styles.rewardListColumnWrapper}
            renderItem={({item,index}) => this.renderRewardItem(item,index)}
          />
          <ActivityIndicator
            animating={reward.loading}
            toast
            size="large"
            text={i18n.t("office.reward.indicator.loading")}
          />
        </View>
        <View style={_styles.mainViewRightSidePanel}>
          {
            showEditForm ?
            <RewardEditForm
              reward={reward.editingReward}
              products={products}
              onCancel={() => this.cancelEditReward()}
              onSave={(data) => this.saveReward(data)}
            /> :
            <RewardTips />
          }
          <ActivityIndicator
            animating={reward.saving}
            toast
            size="large"
            text={i18n.t("office.reward.indicator.saving")}
          />
        </View>
      </View>
    );
  }

  render() {
    const { reward } = this.props;
    const showEditForm = !_.isEmpty(reward.editingReward);
    const { products = [] } = reward;

    return (
      <View style={styles.container}>
        <View style={styles.rewardView}>
          { this.renderNavigationBar() }
          { this.renderMainView() }
        </View>
      </View>
    );
  }

  back() {
    // Cancel any editing reward
    this.cancelEditReward();

    this.props.navigation.goBack();
  }

  renderRewardItem(item, index) {
    const _styles = rewardItemStyles;

    if (_.isEmpty(item)) {
      return (
        <View style={_styles.rewardItemContainer}>
          <RewardAddItem
            onPress={() => this.addReward()}
            text="Add Reward"
          />
        </View>
      );
    }

    return (
      <View style={_styles.rewardItemContainer}>
        <RewardItem
          reward={item}
          onEdit={(reward) => this.editReward(reward)}
          onDelete={(rewardId) => this.deleteReward(rewardId)}
        />
      </View>
    );
  }

  addReward(){
    this.props.addNewReward();
  }

  editReward(reward) {
    this.props.editReward(reward);
  }

  validateRewardSavingDate(data, onSuccess, onFail) {
    const { reward, image } = data;
    let error = {};

    const requiredRules = [
      {
        key: 'image',
        condition: (data) => ((data.length !== 0) || !_.isEmpty(image)),
        message: i18n.t("office.reward.form.required.image"),
      },
      {
        key: 'title',
        condition: (data) => (data.length !== 0),
        message: i18n.t("office.reward.form.required.title"),
      },
      {
        key: 'take_points',
        condition: (data) => (isInteger(data)),
        message: i18n.t("office.reward.form.required.takepoints"),
      },
      {
        key: 'product_id',
        condition: (data) => (isInteger(data)),
        message: i18n.t("office.reward.form.required.productid"),
      },
      {
        key: 'sort_order',
        condition: (data) => (isInteger(data)),
        message: i18n.t("office.reward.form.required.sortorder"),
      },
    ];

    for (let rule of requiredRules) {
      const { key, condition, message } = rule;
      if (!condition(reward[key])) {
        error = {
          message
        };
        break;
      }
    }

    if (!_.isEmpty(error)) {
      onFail && onFail(error);
    } else {
      onSuccess && onSuccess();
    }
  }

  saveReward(data) {
    this.validateRewardSavingDate(
      data,
      () => this.props.saveReward(data),
      (error) => Toast.info(error.message, 3, null, false),
    );
  }

  deleteReward(rewardId) {
    Modal.alert('', i18n.t("office.reward.alert.deleterewardmessage"), [
      { text: i18n.t("btns.cancel"), onPress: () => {}, style: 'cancel' },
      { text: i18n.t("btns.okText"), onPress: () => this.props.deleteReward(rewardId) },
    ]);
  }

  cancelEditReward() {
    this.props.cancelEditReward();
  }
}

/* StyleSheet =============================================================== */

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
    flexDirection: 'row',
  },
  rewardView: {
    flex: 1,
    backgroundColor: "#090d17",
  },
});

const navigationBarStyles = StyleSheet.create({
  navigationBar: {
    height: scaleSize(80),
    flexDirection: 'row',
    paddingHorizontal: scaleSize(30),
    alignItems: 'center',
    backgroundColor: "#151c2e",
  },
  navigationBackButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingRight: scaleSize(50),
  },
  leftArrowImage: {
    width: scaleSize(17),
    height: scaleSize(30),
  },
  backButtonText: {
    color:"#fff",
    paddingHorizontal: scaleSize(30),
  },
  navigationTitle: {
    width: scaleSize(1480),
    alignItems: 'center',
  },
  navigationTitleText: {
    color: "#fff",
    fontSize: scaleSize(30),
  },
  navigationRightButtonGroup: {
    justifyContent: 'flex-end',
    alignItems: 'center',
    flexDirection: 'row',
    width: scaleSize(120),
    flex: 1,
  },
  addButton: {
    paddingLeft: scaleSize(50),
  },
  addButtonIcon: {
    width: scaleSize(30),
    height: scaleSize(30),
  },
});

const mainViewStyles = StyleSheet.create({
  mainViewContainer: {
    flex: 1,
    flexDirection: 'row',
  },
  mainViewMainPanel: {
    flex: 1,
  },
  rewardList: {
    flex: 1,
  },
  rewardListColumnWrapper: {
    paddingHorizontal: scaleSize(30),
  },
  mainViewRightSidePanel: {
    width: scaleSize(550),
    backgroundColor: "#232b40",
  },
});

const rewardItemStyles = StyleSheet.create({
  rewardItemContainer: {
    marginRight: scaleSize(12),
    width: scaleSize(350),
    height: scaleSize(610),
    paddingTop: scaleSize(50),
  },
});

function isInteger(value) {
  let x;
  if (isNaN(value)) {
    return false;
  }

  x = parseFloat(value);
  return (x | 0) === x;
}

function mapStateToProps({ reward }) {
  return { reward };
}

export default connect(mapStateToProps, rewardActions)(OfficeRewards);
